﻿using eLoop.Netty;
using System;
using System.Threading;

namespace eLoop;

sealed class SingleEventScheduler : ASingleScheduler, eLoop.Netty.IRunnable
{
    private static long index = 0;
    
    public SingleEventScheduler()
    {
        this.Id = $"thread:{Interlocked.Read(ref index)}";
        this.Name = $"work_thread_{Interlocked.Read(ref index)}";
        Interlocked.Increment(ref index);

        this.executor = new SingleThreadEventExecutor(Name, TimeSpan.FromMilliseconds(100));
    }
    
    private SingleThreadEventExecutor executor;
    
    protected override void ExecuteLoop()
    {
        this.executor.Execute(this);
    }

    public void Run()
    {
        base.DeliverWorks();
    }

    public override void Dispose()
    {
        if (this.IsDisposed)
        {
            return;
        }
        
        executor.ShutdownGracefullyAsync().GetAwaiter().GetResult();
        base.Dispose();
    }

    
}